package cn.nuc.controller.system.before;

import cn.nuc.pojo.system.User;
import cn.nuc.service.system.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController2 {
    @Autowired
    private IUserService userService;
    @PostMapping
    public String changePwd(String urlActive, String password , String newPw , String newPw2 , HttpServletRequest request) throws IOException {
        User user = (User) request.getSession().getAttribute("user");
        boolean checkpw = BCrypt.checkpw(password, user.getPassword());
        String pwdMsg = "";
        if(checkpw){
            if(newPw.equals(newPw2)){
                String hashpw = BCrypt.hashpw(newPw, BCrypt.gensalt());
                user.setPassword(hashpw);
                userService.saveOrUpdate(user);
                pwdMsg = "修改成功！";
            }else{
                pwdMsg = "两次输入的新密码不一致!修改失败";
            }
        }else {
            pwdMsg = "原密码错误！修改失败";
        }
        request.getSession().setAttribute("pwdMsg" , pwdMsg);
        return "redirect:/" + urlActive;
    }
}
